package controllers

import (
	"weiboxs.com/new_h_glasses/enums"
	"weiboxs.com/new_h_glasses/models"
	"weiboxs.com/new_h_glasses/utils"
)

type ErpClassController struct {
	BaseController
}

func (c *ErpClassController) Prepare() {
	c.BaseController.Prepare()
	c.Data["activeSidebarUrl"] = "/class/index"
}

func (c *ErpClassController) Index() {

	c.checkAuthor("class/index")

	c.display("", "erpclass/index_footerjs.html")

}

func (c *ErpClassController) DataGrid() {

	tree := models.ErpClassLists()

	c.jsonDataTable(0, tree)
}

func (c *ErpClassController) Edit() {

	c.checkAuthor("class/edit")

	if c.Ctx.Input.IsPost() {
		c.Save()
	}

	id, _ := c.GetInt64(":id")

	var err error

	m := new(models.ErpClass)
	m.Id = id

	if id > 0 {
		m, err = models.GetErpClassById(id)
		if err != nil {
			c.pageError("找不到指定数据")
		}
	} else {
		m.ParentId = 0
	}

	tree := models.ErpClassTree()
	c.Data["parent"] = tree

	c.Data["m"] = m
	c.Data["style"] = models.ErpClassStyle()

	c.display("", "erpclass/edit_footerjs.html", "shared/layout_dialog.html")

}

func (c *ErpClassController) Save() {

	m := models.ErpClass{}

	if err := c.ParseForm(&m); err != nil {
		c.jsonResult(enums.JRCodeFailed, "提交参数错误", "")
	}

	if m.Id == 0 { //新增
		if _, err := models.ErpClassAdd(&m); err != nil {
			c.jsonResult(enums.JRCodeFailed, "新增失败:"+err.Error(), "")
		} else {
			c.jsonResult(enums.JRCodeSucc, "新增成功", "")
		}
	} else { //修改
		if mr, err := models.GetErpClassById(m.Id); err != nil {
			c.jsonResult(enums.JRCodeFailed, "获取失败:"+err.Error(), "")
		} else {
			m.Status = mr.Status
		}

		f, _ := utils.ReflectModelFields(&m)

		if err := m.ErpClassEdit(f...); err != nil {
			c.jsonResult(enums.JRCodeFailed, "修改失败:"+err.Error(), "")
		} else {
			c.jsonResult(enums.JRCodeSucc, "修改成功", "")
		}
	}

}

func (c *ErpClassController) Delete() {

	c.checkAuthor("class/delete")

	id, _ := c.GetInt64("id")

	if err := models.ErpClassDel(id); err != nil {
		c.jsonResult(enums.JRCodeFailed, "删除失败:"+err.Error(), "")
	} else {
		c.jsonResult(enums.JRCodeSucc, "删除成功", "")
	}
}
